#include "AbstractFactory.h"
#include "AppBase.h"
#include "TCPClient.h"
#include <boost/asio/spawn.hpp>
#include <iostream>

using namespace UTILS;

TCPClient::TCPClient(boost::asio::io_context &io, const std::string &ip,
                     const uint32_t port, const uint32_t code)
    : m_ReadWriteMgr_(std::make_shared<SerializaReadWrite>(io.get_executor())),
      m_ip_(ip), m_port_(port), m_code_(code) {}

void TCPClient::init() {
  auto self(shared_from_this());
  boost::system::error_code ec;
  m_ReadWriteMgr_->socket().async_connect(
      boost::asio::ip::tcp::endpoint(
          boost::asio::ip::address::from_string(m_ip_), m_port_),
      [self, this](const boost::system::error_code &ec) {
        if (!ec) {
          create_session();
        } else {
          throw std::runtime_error(ec.message());
        }
      });
}

void TCPClient::create_session() {
  std::cout << "TCPClient::create_session" << std::endl;
  std::shared_ptr<AppBase> appPtr =
      APPFactory(AbstractFactory::FactoryType::TCP_CLIENT_APP)
          .getObject<AppBase>(m_code_);
  appPtr->start(m_ReadWriteMgr_);
}
TCPClient::~TCPClient() { std::cout << "~TCPClient" << std::endl; }
